/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require("mongoose");
var DataCollection = require("../models/cate.model");


//数据存储
exports.create = function (req,res,next) {
	const dataColl = new DataCollection(req.body);
	console.log(req.body)
	dataColl.save().then(data=>{
		res.json(data)
	})
}

//获取一个对象
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findById(id,(err,data)=>{
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataCollection.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
		res.json(data);
	})
}

//删除
exports.remove = function (req,res,next) {
	var id = req.params.id;
	var ids = [];
	DataCollection.findOne({_id:id},(err,pre)=>{
		if(pre){
			ids[0] = id;
			pre.getChildren().then((child)=>{
				var len = child.length;
				for(var i=0;i<len;i++){
					ids.push(child[i]._id);
				}
				// console.log(pre._id);
				DataCollection.remove({ _id : {$in : ids}})
				.then(data=>{
					res.json({"msg":"deletes success","status":200,"data":ids});
				})
			})
		}else{
			res.json({"msg":"deletes fail","status":404});
		}
	})
}


//树形查询
function reverseTree(data, pid){
	var result = [];
	var	temp;
	// 将一个DataModel的object转成了JS的Object
	var data = JSON.parse(JSON.stringify(data));  
	for(var i in data){
		if(data[i].parentId == pid){
			result.push(data[i]);
			//找以该节点为父节点的孩子节点	
			temp = reverseTree(data, data[i]._id);
			//如果找的孩子节点，放到父节点的额children中	
			if(temp.length>0){
				data[i].children = temp;
			}
		}
	}
	//将找到的节点返回出去
	return result
}


exports.list = function(req,res,next){
	var type = req.params.type;
	DataCollection.find({type:type},(err,data)=>{
		var rpTree = reverseTree(data, null);
		res.json(rpTree);
	})
	
}

//获取节点的儿子
exports.getFamily = function(req,res,next){
	var id = req.params.id;
	var ids = [];
	console.log(id)
	DataCollection.findOne({_id:id},(err,pre)=>{
		if(pre){
			ids[0] = id;
			pre.getChildren().then((child)=>{
				var len = child.length;
				for(var i=0;i<len;i++){
					ids.push(child[i]._id);
				}
				console.log(ids);
				res.json(ids)
			})
		}
	})
} 

